package com.Iconcat.system.controller;


import com.Iconcat.system.entity.CatAdmin;
import com.Iconcat.system.entity.CatMenu;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.CatAdminService;
import com.Iconcat.system.service.CatMenuService;
import com.Iconcat.system.util.JwtUtil;
import com.Iconcat.system.util.Md5Util;
import com.Iconcat.system.util.MyUtils;
import com.Iconcat.system.util.VertiCodeUtill;
import com.Iconcat.system.vo.LoginResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 后台管理员信息 前端控制器
 * </p>
 *
 * @author zzq
 * @since 2023-11-17
 */
@RestController
@RequestMapping("/cat-admin")
@Api(value = "系统管理员模块", tags = "系统管理员接口")
@CrossOrigin
@Slf4j
@Scope("prototype")
public class CatAdminController {
    @Resource
    private CatAdminService catAdminService;
    @Resource
    private CatMenuService catMenuService;

    @PostMapping("/login")
    public Result login(@RequestBody CatAdmin catAdmin, HttpServletRequest req) throws IOException {
//
        String username = catAdmin.getUsername();
        String password = catAdmin.getPassword();
        QueryWrapper<CatAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        CatAdmin admin = catAdminService.getOne(wrapper);
        Md5Util.md5(password);
        if (admin == null) {
            return Result.error().message("用户不存在");
        }
//        if (MyUtils.isEmpty(imagecode)){ return Result.error().message("验证为空");}

        HttpSession session = req.getSession(true);
//        String imgsrc2= (String)session.getAttribute("checkcode_session");
//        System.out.println("sessionCode:"+imgsrc2);
        String token = JwtUtil.setToken(admin.getUsername());
        HashMap map = new HashMap();
        map.put("token", token);

        // 查询用户权限信息，这里假设权限信息与菜单有关联
        List<CatMenu> permissions = catMenuService.getPermissionsByAdminId(admin.getAuid());
        // 构造登录成功的响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setAdminId(admin.getAuid());
        response.setPermissions(permissions);
//        System.out.println(imagecode+"+"+imgsrc2);
//        if(!imagecode.equals(imgsrc2)){
//            return Result.error().message("验证码不正确");
//        }
//        final  String sessionVerifyCode=req.getSession().getAttribute("verifyCode");
//        System.out.println(sessionVerifyCode);

//        if (sessionVerifyCode.equals(imagecode)){
//            return Result.ok().data("admin",admin).message("success");
//        }
//        chatHandler.sendMessageToAdmin(admin.getAuid(),"登录成功");
        return Result.ok().data("admin", admin).message("登录成功").token("token",token);

    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String token = "";
//        Cookie[] cookies = request.getCookies();
//        for (int i = 0; i < cookies.length; i++) {
//            Cookie cookie = cookies[i];
//            if ("token".equals(cookie.getName())) {
//                token = cookie.getValue();
//            }
//        }
//        if (token==null){
//            return Result.error().message("已经退出");
//        }
        return Result.ok().message("退出成功");
    }
    @GetMapping("/getUserInfo/{id}")
    public Result userInfo(@PathVariable(value = "id") Integer admin_id, @RequestHeader("Authorization") String token) {
        System.out.println("Received admin_id: " + admin_id);
        CatAdmin admin = catAdminService.getById(admin_id);
        // 判断 token 是否为空
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.error().message("未提供有效的身份验证信息");
        }

        // 去掉 "Bearer " 前缀，获取实际的 token 值
        String actualToken = token.substring(7);

        if (admin == null) {
            return Result.error().message("用户不存在");
        }
        if (isValidToken(actualToken)) {
            // 在这里编写你的业务逻辑
            // ...
            return Result.ok().data("admin", admin).message("获取成功");
        } else {
            return Result.error().message("身份验证失败");
        }
    }

    private boolean isValidToken(String token) {
        // 在这里进行 token 的验证逻辑，比如验证是否过期、是否合法等
        // 你需要根据你的具体实现来编写 isValidToken 方法
        // 这里只是一个示例，需要根据实际情况修改
        return token != null && !token.isEmpty();
    }

    @GetMapping("/findAdmin")
    public Result findAdmin() {
        List<CatAdmin> list = catAdminService.list();
        return Result.ok().data("admin", list);
    }

    @GetMapping("/{id}")
    public Result queryByKey(@PathVariable("id") Integer admin_id) {
        CatAdmin id = catAdminService.getById(admin_id);
        return Result.ok().data("matter", id);
    }

    @PostMapping("/updateById")
    public Result updateById(@RequestBody CatAdmin cgtAdmin) throws Exception {
        Boolean admin = catAdminService.updateById(cgtAdmin);
        if (admin) {
            return Result.ok().message("修改成功");
        } else {
            return Result.error().message("修改失败");
        }
    }

    @PostMapping("/addAdmin")
    public Result addAdmin(@RequestBody CatAdmin cgtAdmin) {
        try {
            catAdminService.save(cgtAdmin);
            return Result.ok();
        } catch (Exception e) {
            //打印日志
            return Result.error();
        }
    }

    @PostMapping("/delete/id")
    public Result deleteById(@RequestParam("admin_id") Integer admin_id) {
        Boolean admin = catAdminService.removeById(admin_id);
        if (admin) {
            return Result.ok().message("删除成功");
        } else {
            return Result.error().message("删除失败");
        }
    }

    @PostMapping("/deleteIds")
    public Result deleteByIds(@RequestParam("ids") Collection ids) {
        Boolean admin = catAdminService.removeByIds(ids);
        System.out.println(admin);
        if (admin == false) {
            return Result.error().message("删除失败或数据不存在");
        }
        return Result.ok().message("删除成功");
    }

    @PostMapping("/updateByPwd")
    public Result modifyByPwd(@RequestParam(required = true, value = "oldPassword") String oldPassword,
                              @RequestParam(required = true, value = "newPassword") String newPassword, @RequestParam("admin_id") Integer admin_id) {
        CatAdmin user = catAdminService.getById(admin_id);
        if (!oldPassword.equals(user.getPassword())) {
            return Result.error().message("旧密码错误");
        }
        int p = catAdminService.updateByPwd(admin_id, newPassword);
        return p == 1 ? Result.ok().message("密码修改成功") : Result.error().message("修改失败");
    }
//    @RequestMapping("/verifyCode.jpg")
//    @ApiOperation(value="verifyCode",notes = "code信息")
//    protected  void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        final VertiCodeUtill vertiCodeUtill=VertiCodeUtill.getInstance();
//        final ByteArrayInputStream image=vertiCodeUtill.getImage();
//        final StringBuilder verifyCode=vertiCodeUtill.getVercode();
////        HttpSession session=request.getSession();
////        session.setAttribute("checkcode_session", verifyCode);
////        System.out.println( request.getSession().getAttribute("verifyCode"));
//        response.setContentType("image/jpeg");
//
//        byte[] bytes=new byte[1024];
//        HttpSession session=request.getSession();
//         session.setAttribute("verifyCode",verifyCode);
//        System.out.println( request.getSession().getAttribute("verifyCode"));
//        try (final ServletOutputStream out=response.getOutputStream()){
//          while (image.read(bytes)!=-1){
//              out.write(bytes);
//          }
//        }
//    }
//    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        imageCode(request,response);
//    }
}

